package com.et.logger

import android.util.Log
import java.io.File
import java.io.FileWriter
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.Executor
import java.util.concurrent.Executors
import kotlin.collections.HashMap

object TAGS {
    const val launch: String = "tag_launch"
    const val protocol: String = "tag_protocol"
    const val machine: String = "tag_machine"
    const val vending: String = "tag_vending"
}

class ELog {
    companion object {
        private val logWriter: LogWriter = LogWriter

        fun init(saveDir: File) {
            logWriter.putRootDir(saveDir)
        }

        fun d(tag: String, content: String) {
            if (BuildConfig.DEBUG) Log.d(tag, content)
            logWriter.writeLog(tag, content)
        }
    }
}

object LogWriter {

    private val sdf = SimpleDateFormat("yyMMdd HH:mm:ss SSS", Locale.CHINA)
    private val thread: Executor = Executors.newSingleThreadExecutor()
    private var rootFileDir: File? = null
    private var todayEndTime = 0L
    private val tagFileMap = HashMap<String, File>()


    fun putRootDir(dir: File) {
        this.rootFileDir = dir
        if (dir.isDirectory) dir.mkdirs()
        val current = System.currentTimeMillis() //当前时间毫秒数
        val zero =
            current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().rawOffset //今天零点零分零秒的毫秒数
        todayEndTime = zero + 24 * 60 * 60 * 1000 - 1 //今天23点59分59秒的毫秒数
    }

    fun writeLog(tag: String, content: String) {
        rootFileDir ?: return
        logFile(tag)?.let { file ->
            thread.execute {
                FileWriter(file, true).use {
                    it.append(sdf.format(System.currentTimeMillis()))
                        .append(" ")
                        .append(content)
                        .append("\n")
                }
            }
        }
    }

    private fun logFile(tag: String): File? {
        rootFileDir ?: return null
        if (!rootFileDir!!.exists()) rootFileDir?.mkdirs()
        if (rootFileDir!!.exists()) {
            var nowLogFile = tagFileMap[tag]
            if (nowLogFile == null) {
                nowLogFile = createFile(rootFileDir!!, tag)
                tagFileMap[tag] = nowLogFile
            } else if (System.currentTimeMillis() > todayEndTime) {
                nowLogFile = createFile(rootFileDir!!, tag)
            }
            if (nowLogFile.exists()) {
                return nowLogFile
            }
        }
        return null
    }

    private fun createFile(rootDir: File, name: String): File {
        SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).let { sdf ->
            return File(
                rootDir,
                "${sdf.format(System.currentTimeMillis() + 60 * 1000)}.$name.txt"
            ).also {
                if (!it.exists()) it.createNewFile()
            }
        }
    }
}